<template>
    <span>
<!--        {{formData[propName]}}-->
        <!--        {{currentValue}}-->
        <el-select v-model="currentValue" :placeholder="placeholder"
                   :disabled="disabled||sksReadonly"
                   :filterable="filterable"
                   :multiple="false"
                   :clearable="clearable"
                   @change="handleChangeValue"
                   :style="styles"
                   @visible-change="handleVisibleChange"
                   :remote="remote"
                   :remote-method="remoteMethod"
                   :loading="lookupDomainTable.loading"
        >
          <template slot="prefix" v-if="$slots.prefix">
            <slot name="prefix"></slot>
          </template>
            <el-option
                v-for="item in lookupDomainTable.list"
                :key="item[optionKey]"
                :value="item[optionKey]"
                :label="defaultFormatLabel(item)"
                class="item-option"
                :disabled="sksReadonly||optionDisabledFunc(item)"
            >
                <!--只会搜索 :label 中的内容-->
                <template>
                    <slot name="optionLabel" :item="item"></slot>
                </template>
            </el-option>
        </el-select>
    </span>
</template>

<script>
//用于业务选择
import {
    deepCopy,
    equalsObjectJson,
    findRowInListFromAttrName,
    isNullOrUndefined,
    safeGet,
    resetSksTableBefore, setSksTableDataByPage, strIsEmpty, mergeFromObject
} from "../../../core";
import {newSksTable} from "../../../sks-model-utils";


export default {
    name: "SksSelectSingleByLookupController",
    props: {
        /**
         * true: 显示为只读组建
         ***/
        sksReadonly: {
            type: Boolean,
            default: false
        },
        method: {
            default: 'post'
        },
        //form表单数据
        formData: [Object],
        //属性名
        propName: [String],
        //用于清空校验,已弃用
        formRef: Object,
        //禁用选项方法,true: 禁用选项
        optionDisabledFunc: {
            type: Function,
            default: (item) => {
                return false
            }
        },
        //值类型,number/string
        //会将 optionKey对应的值 转换为 number/string
        //转换逻辑还未写
        valueType: {
            type: String,
            default: 'number',
        },
        //点击下拉框时重新查找数据
        visibleChangeLookup: {
            type: Boolean,
            default: true,
        },
        //如果该行信息下拉选项中不存在,将会插入到list最后一行,因为第一行可能会有 unshiftOptionList 添加的标题,所以添加到最后
        //避免下拉数据被过滤掉了不显示
        valueRowList: [Array],
        disabled: [Boolean],
        //是否为远程搜索
        remote: [Boolean],
        clearable: Boolean,
        filterable: {
            type: Boolean,
            default: true,
        },
        placeholder: {
            type: String,
            default: '请选择或搜索'
        },
        //宽度对于 1000px 无效
        //        100%   有效
        width: [String],
        buttonText: [String],
        /**
         * 集合存放key的字段名
         * 例如: userId   depId
         ***/
        optionKey: [String],
        optionLabel: [String],
        //显示选中后的信息,搜索也会根据该信息
        formatOptionLabel: [Function],

        //如果对应选择列不存在,添加到顶部位置的数组,
        //数据类型需要保持与字段类型一致
        unshiftOptionList: Array,

        requestUrl: [String],
        queryParams: Object,
        //true: 禁用查询,某些条件不满足时,不进行查询
        queryDisable: Boolean,
        /**
         * 自动设置映射
         * 选择行 lookupProp 属性的值设置到 form 对应的属性
         [
         {
                lookupProp: 'companyName',
                formProp: 'virtualCompanyName',
              },
         ]
         */
        lookupMap: {
            type: Array,
            default() {
                return []
            }
        }
    },
    computed: {
        styles() {
            let style = {};
            if (this.width) {
                style.width = `${this.width}`;
            } else {
                style.width = `100%`;
            }
            return style;
        },
    },
    watch: {
        queryDisable: {
            handler(val) {
                if(!val){
                    this.lookupList()
                    console.log("lookupList.queryDisable")
                }
            },
            immediate: true,
            deep: true,
        },
        queryParams: {
            handler(val) {
                // console.log("queryParams",this.queryParams)
                if (!equalsObjectJson(this.queryParamsCache,this.queryParams)) {
                    this.queryParamsCache=this.queryParams
                    // console.log("watch.queryParams,this.queryParamsCache,this.queryParams",this.queryParamsCache,this.queryParams)
                    this.lookupList()
                }
            },
            immediate: true,
            deep: true,
        },
        valueRowList: {
            handler(val) {
                this.mergeValueRowToList()
            },
            immediate: true,
        },
        formData: {
            handler(val) {
                console.log(`watch.formData.${this.propName}=`,safeGet(this.formData,this.propName),val)
                this.watchFormDataPropNameValue()
            },
            immediate: true,
            deep: true,
        },
    },
    data() {
        return {
            lookupDomainTable: newSksTable(),
            //
            currentValue: undefined,
            //查询缓存
            queryParamsCache: undefined,
        }
    },
    created() {
    },
    mounted() {
        // console.log("sksSelect mounted")
        // if(!this.lookupDomainTable.loading){
        //     this.lookupList()
        // }
    },
    methods: {
        watchFormDataPropNameValue() {
            //console.log(`formData.watchValue.`, this.formData, `[${this.propName}]`)
            if (isNullOrUndefined(this.formData)) {
                this.watchValue(undefined)
                return
            }
            if (isNullOrUndefined(this.propName)) {
                this.watchValue(undefined)
                return
            }
            //console.log(`watchValue.`, this.formData, `[${this.propName}]${this.formData[this.propName]}`)
            this.watchValue(this.formData[this.propName])
        },
        watchValue(val) {
            if (val !== this.currentValue) {
                //console.log(`watchValue.${this.propName}.val=`, val, "currentValue=", this.currentValue)
                if (this.valueType === 'string') {
                    this.currentValue = isNullOrUndefined(val) ? val : `${val}`;
                } else {
                    this.currentValue = val;
                }
                this.updateValue()
                // if(val != this.currentValue){
                //     this.lookupList()
                // }
            }
        },
        handleVisibleChange(e) {
            if (e && this.visibleChangeLookup) {
                this.lookupList();
            }
            // console.log("sksSelect handleVisibleChange",e)
        },
        remoteMethod(lookupSearchValueListCustomize) {
            // console.log("query",lookupSearchValueListCustomize)
            if (lookupSearchValueListCustomize !== '') {
                this.lookupList(lookupSearchValueListCustomize)
            } else {
                this.lookupList()
            }
        },
        lookupList(lookupSearchValueListCustomize, queryDisable = this.queryDisable) {
            if (queryDisable) {
                return
            }
            if (strIsEmpty(this.requestUrl)) {
                this.sksUtils.msgError("requestUrl不能为空")
                return
            }
            let queryParams = mergeFromObject({}, this.queryParams, {
                // pageNum: this.selectTable.queryParams.pageNum,
                // pageSize: this.selectTable.queryParams.pageSize,
                pageNum: 1,
                //这里暂不考虑使用远程搜索每页限制,因为远程搜索时还要考虑原记录ID在当前页不存在时的情况
                pageSize: this.remote ? 50 : 0xffff,
            })
            if (isNullOrUndefined(queryParams.sksParams)) {
                queryParams.sksParams = {}
            }
            resetSksTableBefore(this.lookupDomainTable)
            queryParams.sksParams.lookupSearchValueListCustomize = lookupSearchValueListCustomize
            this.$SKS_PLUGIN_EL_ERP.request({
                url: this.requestUrl,
                headers: {
                    repeatSubmit: false,
                },
                method: this.method,
                data: queryParams
            }).then(saRes => {
                console.log("saRes",saRes.data)
                setSksTableDataByPage(this.lookupDomainTable, saRes.data)
                let list = saRes.data.list;
                for (let item of list) {
                    if (this.valueType === 'string') {
                        //所有选择的值转换为字符串
                        item[this.optionKey] = '' + item[this.optionKey]
                    } else {
                        //所有选择的值转换为字符串
                        item[this.optionKey] = item[this.optionKey]
                    }
                }
                if (strIsEmpty(lookupSearchValueListCustomize)) {
                    if (this.unshiftOptionList) {
                        for (let unshiftOption of this.unshiftOptionList) {
                            if (isNullOrUndefined(unshiftOption)) {
                                continue
                            }
                            let optionKeyZeroValue = unshiftOption[this.optionKey]
                            let tmp = findRowInListFromAttrName(list, this.optionKey, optionKeyZeroValue, true)
                            if (tmp == undefined) {
                                list.unshift(unshiftOption)
                            }
                        }
                    }

                }
                this.mergeValueRowToList(list)
            }).catch(e => {

            })
        },
        mergeValueRowToList(list = this.lookupDomainTable.list) {
            //console.log("mergeValueRowToList.list=",list,",valueRow",this.valueRowList,",optionKey=",this.optionKey)
            if (!isNullOrUndefined(this.valueRowList)) {
                for (let valueRow of this.valueRowList) {
                    if (isNullOrUndefined(valueRow) || strIsEmpty(this.optionKey)) {
                        continue
                    }
                    if (!isNullOrUndefined(valueRow[this.optionKey])) {
                        let row = findRowInListFromAttrName(list, this.optionKey, valueRow[this.optionKey]);
                        //console.log("mergeValueRowToList.findRowInListFromAttrName=",row)
                        if (isNullOrUndefined(row)) {
                            let item = deepCopy(valueRow)
                            //console.log("mergeValueRowToList.valueRow-item=",item)
                            if (this.valueType === 'string') {
                                //所有选择的值转换为字符串
                                item[this.optionKey] = '' + item[this.optionKey]
                            }
                            list.push(item)
                        }
                    }
                }
            }

        },
        defaultFormatLabel(item) {
            if (isNullOrUndefined(this.formatOptionLabel)) {
                return this.optionLabel === undefined ? item[this.optionKey] : item[this.optionLabel]
            }
            return this.formatOptionLabel(item)
        },
        handleChangeValue(val) {
            // console.log("val=",val)
            let row = {}
            if (this.currentValue === '') {
                this.currentValue = undefined
            }
            if (!isNullOrUndefined(this.currentValue)) {
                row = findRowInListFromAttrName(this.lookupDomainTable.list, this.optionKey, this.currentValue);
            }
            if (isNullOrUndefined(row)) {
                row = {}
            }
            //设置关联属性值
            for (let lookupTmp of this.lookupMap) {
                // console.log("lookupTmp",lookupTmp,row)
                this.formData[lookupTmp.formProp] = row[lookupTmp.lookupProp]
            }
            let oldVal=undefined
            if (!isNullOrUndefined(this.formData) && !isNullOrUndefined(this.propName)) {
                oldVal=this.formData[this.propName]
            }
            //更新前触发selected
            this.$emit('selected', row, this.currentValue,oldVal)
            this.updateValue(this.currentValue)
        },
        updateValue(newVal = this.currentValue) {
            // console.log("sksSelectSingleByLookupService.updateValue",this.formData,this.propName,newVal)
            let oldVal=undefined
            if (!isNullOrUndefined(this.formData) && !isNullOrUndefined(this.propName)) {
                oldVal=this.formData[this.propName]
                this.formData[this.propName] = newVal
            }
            if (!isNullOrUndefined(newVal)) {
                this.$emit('clearValidate', this.propName)
                // this.formRef?.clearValidate(this.propName)
                // setTimeout(()=>{
                //     this.formRef?.clearValidate(this.propName)
                // },500)
            }
            this.$emit("input", {newVal,oldVal});
            this.$emit("change", {newVal,oldVal});

        },
    }
}
</script>

<style scoped>

</style>


<!--
                         @clearValidate="clearFormValidate"

                            组织
                            <sksSelectSingleByLookupController
                                :queryParams="{}"
                                request-url="/system/lookupOrganize"
                                :formData="form"
                                prop-name="orgId"
                                valueType="string"
                                option-key="orgId" option-label="orgName"
                                :option-disabled-func="(item)=>item.status == 1"
                            >
                            </sksSelectSingleByLookupController>

                            地点
                            <sksSelectSingleByLookupController
                                :queryParams="{}"
                                request-url="/system/lookupSite"
                                :formData="form"
                                prop-name="siteId"
                                valueType="string"
                                option-key="siteId" option-label="siteName"
                                :option-disabled-func="(item)=>item.status == 1"
                            >
                            </sksSelectSingleByLookupController>

                            选择人员参考号
                            <sksSelectSingleByLookupController
                                :queryParams="{reference: 'int'}"
                                request-url="/goldwarehouse/personReference/lookup"
                                :formData="form"
                                prop-name="nickName"
                                valueType="string"
                                option-key="personReference" option-label="personName"
                                :format-option-label="(item)=>baseFormatOptionLabel({ item: item, optionKey: `personReference`, relationshipNameList: [`personName`] })"
                            >

                            </sksSelectSingleByLookupController>


                            字典
                            <sksSelectSingleByLookupController
                                :queryParams="{dictType: `sys_company_list`}"
                                request-url="/system/dict/data/lookup"
                                :formData="form"
                                prop-name="intpersonCoLabel"
                                valueType="string"
                                option-key="dictValue" option-label="dictLabel"
                            >
                            </sksSelectSingleByLookupController>

                            岗位
                            <sksSelectSingleByLookupController
                                :queryParams="{}"
                                request-url="/system/post/lookup"
                                :formData="form"
                                prop-name="intpersonPositionId"
                                valueType="string"
                                option-key="postId" option-label="postName"
                                :option-disabled-func="(item)=>item.status == 1"
                            >
                            </sksSelectSingleByLookupController>
-->

